package com.google.project.client.ProjectManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.project.client.Service.ProjectStaffService;
import com.google.project.client.Service.ProjectStaffServiceAsync;
import com.google.project.client.Service.SpecializeService;
import com.google.project.client.Service.SpecializeServiceAsync;
import com.google.project.client.Service.UsersService;
import com.google.project.client.Service.UsersServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectStaffDTO;
import com.google.project.shared.SpecializeDTO;
import com.google.project.shared.UsersDTO;

public class PMProjectStaff extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField TextBox txtCode;
	@UiField TextBox txtName;
	@UiField ListBox cbSpecialize;
	@UiField ListBox cbExperient;
	@UiField ListBox cbStatus;
	@UiField(provided = true) CellTable<ProjectStaffDTO> ctbSearch = new CellTable<ProjectStaffDTO>();
	@UiField SimplePager pagerSearch;
	@UiField Button btnRegistion;
	@UiField Button btnRemove;
	@UiField Button btnBack;
	@UiField Button btnAssignTask;
	
	private final SpecializeServiceAsync specService = GWT.create(SpecializeService.class);
	private final UsersServiceAsync userService = GWT.create(UsersService.class);
	private final MultiSelectionModel<ProjectStaffDTO> selectionModel = new MultiSelectionModel<ProjectStaffDTO>();
	private final ProjectStaffServiceAsync projectStaffService = GWT.create(ProjectStaffService.class);
	private final List<ProjectStaffDTO> projectStaffList = new ArrayList<ProjectStaffDTO>();
	private final List<UsersDTO> userList = new ArrayList<UsersDTO>();
	private final String pjId;
	private int regisOrRemoveFlag;	//Gia tri flag = 0: dung cho Xac nhan nhan vien vao du an
									//Gia tri flag = 1: dung cho Rut nhan vien khoi du an
	
	interface Binder extends UiBinder<Widget, PMProjectStaff> {
	}
	public PMProjectStaff(String projectId) {
		initWidget(binder.createAndBindUi(this));
		this.pjId = projectId;
		initCbSpecialize();
		initCbExperient();
		initCbStatus();
		initCellTable();
		bindData(projectId);
	}
	
	//Khoi tao gia tri Combobox: Chuyen mon
	public void initCbSpecialize() {
		// TODO Auto-generated method stub
		specService.getSpecList(new AsyncCallback<List<SpecializeDTO>>() {

			@Override
			public void onSuccess(List<SpecializeDTO> result) {
				cbSpecialize.addItem("---Tất cả---", "0");
				for (SpecializeDTO specializeDTO : result) {
					cbSpecialize.addItem(specializeDTO.getSpecializeName(),
							specializeDTO.getId());
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
			}
		});
		cbSpecialize.setSelectedIndex(0);
	}
	
	//Khoi tao gia tri Combobox: kinh nghiem
	public void initCbExperient() {
		// TODO Auto-generated method stub
		cbExperient.addItem("---Tất cả---", "0");
		cbExperient.addItem("< 1 năm", "1");
		cbExperient.addItem("1-3 năm", "2");
		cbExperient.addItem("3-5 năm", "3");
		cbExperient.addItem("5-10 năm", "4");
		cbExperient.addItem("> 10 năm", "5");
		cbExperient.setSelectedIndex(0);
	}
	
	//Khoi tao gia tri Combobox: Tinh trang
	public void initCbStatus() {
		cbStatus.addItem("---Tất cả---", "-1");
		cbStatus.addItem("Chưa tham gia", "0");
		cbStatus.addItem("Đang tham gia", "1");
		cbStatus.addItem("Đã hoàn thành", "2");
		cbStatus.setSelectedIndex(-1);
	}
	
	public void initCellTable () {
		//STT
		TextColumn<ProjectStaffDTO> indexColumn = new TextColumn<ProjectStaffDTO>() {
			@Override
			public String getValue(ProjectStaffDTO object) {
				return object.getIndex()+"";
			}
		};
		
		//Check box
		ctbSearch.setSelectionModel(selectionModel,DefaultSelectionEventManager.<ProjectStaffDTO> createCheckboxManager());
		Column<ProjectStaffDTO, Boolean> checkColumn = new Column<ProjectStaffDTO, Boolean>(
				new CheckboxCell(true, false)) {
			@Override
			public Boolean getValue(ProjectStaffDTO object) {
				// Get the value from the selection model.
				return selectionModel.isSelected(object);
			}
		};

		// Ma nhan vien
		TextColumn<ProjectStaffDTO> userCodeColumn = new TextColumn<ProjectStaffDTO>() {
			@Override
			public String getValue(ProjectStaffDTO staff) {
				return staff.getUserCode();
			}
		};

		// Ten nhan vien
		TextColumn<ProjectStaffDTO> userNameColumn = new TextColumn<ProjectStaffDTO>() {
			@Override
			public String getValue(ProjectStaffDTO staff) {
				return staff.getFullName();
			}
		};

		// Chuyen mon
		TextColumn<ProjectStaffDTO> specializeColumn = new TextColumn<ProjectStaffDTO>() {
			@Override
			public String getValue(ProjectStaffDTO staff) {
				return staff.getSpecializeName();
			}
		};

		// Kinh nghiem
		TextColumn<ProjectStaffDTO> experientColumn = new TextColumn<ProjectStaffDTO>() {
			@Override
			public String getValue(ProjectStaffDTO user) {
				int exp = user.getExperient();
				String result = "";
				if (exp == 1) {
					result += " < 1 năm";
				} else if (exp == 2) {
					result += "1-3 năm";
				} else if (exp == 3) {
					result += "3-5 năm";
				} else if (exp == 4) {
					result += "5-10 năm";
				} else if (exp == 5) {
					result += " > 10 năm";
				}
				return result;
			}
		};

		// startDate
		TextColumn<ProjectStaffDTO> startDate = new TextColumn<ProjectStaffDTO>() {
			@Override
			public String getValue(ProjectStaffDTO staff) {
				return CommonFuntion.convertToDate(new Date(staff.getStartDate()));
			}
		};
		// startDate
		TextColumn<ProjectStaffDTO> dueDate = new TextColumn<ProjectStaffDTO>() {
			@Override
			public String getValue(ProjectStaffDTO staff) {
				return CommonFuntion.convertToDate(new Date(staff.getFinishtDate()));
			}
		};
		// Tinh trang
		TextColumn<ProjectStaffDTO> statusColumn = new TextColumn<ProjectStaffDTO>() {
			@Override
			public String getValue(ProjectStaffDTO staff) {
				int status = staff.getStatus();
				String _status = "";
				if (status == 0) {
					_status += "Chưa tham gia";
				} else if (status == 1) {
					_status += "Đang tham gia";
				} else if (status == 2) {
					_status += "Đã hoàn thành";
				}
				return _status;
			}
		};

		ctbSearch.setWidth("100%", true);
		ctbSearch.setPageSize(5);
		ctbSearch.setPageStart(0);
		ctbSearch.setStyleName("ttable");
		
		ctbSearch.addColumn(indexColumn, "STT");
		ctbSearch.setColumnWidth(indexColumn, 40.0, Unit.PX);

		ctbSearch.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant(""));
		ctbSearch.setColumnWidth(checkColumn, 40.0, Unit.PX);
		checkColumn.setHorizontalAlignment(HasAlignment.ALIGN_LEFT);

		ctbSearch.addColumn(userCodeColumn, "Mã nhân viên");
		ctbSearch.setColumnWidth(userCodeColumn, 15.0, Unit.PCT);

		ctbSearch.addColumn(userNameColumn, "Tên nhân viên");
		ctbSearch.setColumnWidth(userNameColumn, 20.0, Unit.PCT);

		ctbSearch.addColumn(specializeColumn, "Chuyên môn");
		ctbSearch.setColumnWidth(specializeColumn, 15.0, Unit.PCT);

		ctbSearch.addColumn(experientColumn, "Kinh nghiệm");
		ctbSearch.setColumnWidth(experientColumn, 15.0, Unit.PCT);
		
		ctbSearch.addColumn(startDate, "Bắt đầu");
		ctbSearch.setColumnWidth(startDate, 15.0, Unit.PCT);
		
		ctbSearch.addColumn(dueDate, "Kết thúc");
		ctbSearch.setColumnWidth(dueDate, 15.0, Unit.PCT);
		
		ctbSearch.addColumn(statusColumn, "Tình trạng");
		ctbSearch.setColumnWidth(statusColumn, 15.0, Unit.PCT);
	}
	
	public void bindData(String projectId) {
		projectStaffService.getProjectStaffList(projectId,
				new AsyncCallback<List<ProjectStaffDTO>>() {

					@Override
					public void onSuccess(List<ProjectStaffDTO> result) {
						// TODO Auto-generated method stub
						for(int i = 0; i < result.size(); i++) {
							result.get(i).setIndex(i+1);
							projectStaffList.add(result.get(i));
						}
						loadData(result);
					}

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
					}
				});

	}

	protected void loadData(List<ProjectStaffDTO> projectStaffDTO) {
		ListDataProvider<ProjectStaffDTO> dataProvider = new ListDataProvider<ProjectStaffDTO>();

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		List<ProjectStaffDTO> list = dataProvider.getList();
		for (ProjectStaffDTO staff : projectStaffDTO) {
			list.add(staff);
		}
		pagerSearch.setDisplay(ctbSearch);
		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbSearch);
	}
	
	@UiHandler("btnSearch")
	void onBtnSearchClick(ClickEvent event) {
		searchFunction();
	}
	
	//Ham tim kiem
	public void searchFunction() {
		String _code = "";
		String _name = "";
		String _specializeName = "";
		int experient = -2;
		int status = -2;
		
		if(txtName.getText().trim()!= null && !txtName.getText().trim().equals("")){
			_name += txtName.getText().trim();
		}
		
		if(txtCode.getText().trim()!= null && !txtCode.getText().trim().equals("")){
			_code += txtCode.getText().trim();
		}
		
		if(cbSpecialize.getValue(cbSpecialize.getSelectedIndex())!= null && !cbSpecialize.getValue(cbSpecialize.getSelectedIndex()).equals("0")){
			_specializeName += cbSpecialize.getValue(cbSpecialize.getSelectedIndex()).trim();
		}
		
		if(cbExperient.getValue(cbExperient.getSelectedIndex()) != null) {
			experient = Integer.parseInt(cbExperient.getValue(cbExperient.getSelectedIndex()));
		}
		
		if(cbStatus.getValue(cbStatus.getSelectedIndex()) != null) {
			status = Integer.parseInt(cbStatus.getValue(cbStatus.getSelectedIndex()));
		}
		
		Boolean condition = true;
		
		//Viec tim kiem chi dua tren List da duoc lay ra tu DB - listUser
		List<ProjectStaffDTO> temple = new ArrayList<ProjectStaffDTO>();
		
		if((txtName.getText().trim() == null || txtName.getText().trim().equals("")) 
		   && (txtCode.getText().trim() == null || txtCode.getText().trim().equals("")) 
		   && (cbSpecialize.getValue(cbSpecialize.getSelectedIndex()).equalsIgnoreCase("0"))
		   && (cbExperient.getValue(cbExperient.getSelectedIndex()).equalsIgnoreCase("0"))
		   && (cbStatus.getValue(cbStatus.getSelectedIndex()).equalsIgnoreCase("-1"))){
			loadData(projectStaffList);
		} else {
			for(int i = 0; i < projectStaffList.size(); i++) {
				if(txtCode.getText().trim() != null && !txtCode.getText().trim().equals("")) {
					condition = condition && (projectStaffList.get(i).getUserCode().contains(_code));
				}
				if(txtName.getText().trim() != null && !txtName.getText().trim().equals("")) {
					condition = condition && (projectStaffList.get(i).getUserName().contains(_name));
				}
				if(projectStaffList.get(i).getSpecializeID() == null) {
					projectStaffList.get(i).setSpecializeID("0");
				}
				if((cbSpecialize.getValue(cbSpecialize.getSelectedIndex()) != null) && (!cbSpecialize.getValue(cbSpecialize.getSelectedIndex()).equalsIgnoreCase("0"))) {
					condition = condition && (projectStaffList.get(i).getSpecializeID().equals(_specializeName));
				}
				if((cbExperient.getValue(cbExperient.getSelectedIndex()) != null) && (!cbExperient.getValue(cbExperient.getSelectedIndex()).equalsIgnoreCase("0"))) {
					condition = condition && (projectStaffList.get(i).getExperient() == experient);
				}
				if((cbStatus.getValue(cbStatus.getSelectedIndex()) != null) && (!cbStatus.getValue(cbStatus.getSelectedIndex()).equalsIgnoreCase("-1"))) {
					condition = condition && (projectStaffList.get(i).getStatus() == status);
				}
				if(condition) {
					temple.add(projectStaffList.get(i));
				}
				condition = true;
			}
			if(temple != null) {
				loadData(temple);
			} else {
				Window.alert("Không tìm thấy dữ liệu");
				loadData(temple);
			}
		}
	}
	@UiHandler("btnRegistion")
	void onBtnRegistionClick(ClickEvent event) {
		regisOrRemoveFlag = 0;	//Gia tri flag = 0: dung cho Xac nhan nhan vien vao du an
		regisOrRemove(regisOrRemoveFlag);
	}
	@UiHandler("btnRemove")
	void onBtnRemoveClick(ClickEvent event) {
		regisOrRemoveFlag = 1;	//Gia tri flag = 1: dung cho Rut nhan vien khoi du an
		regisOrRemove(regisOrRemoveFlag);
	}
	
	//Ham thuc hien viec xac nhan/rut nhan vien
	public void regisOrRemove(int regisOrRemoveFlag) {
		final int _regisOrRemoveFlag = regisOrRemoveFlag;
		final Set<ProjectStaffDTO> listChecked = selectionModel.getSelectedSet();
		final List<ProjectStaffDTO> pjSDTOList = new ArrayList<ProjectStaffDTO>();
		for(ProjectStaffDTO pjDTO : listChecked) {
			pjSDTOList.add(pjDTO);
		}
		if(pjSDTOList.isEmpty()) {
			if(regisOrRemoveFlag == 0) {
				Window.alert("Bạn chưa chọn nhân viên để xác nhận vào dự án!");
			} else if(regisOrRemoveFlag == 1) {
				Window.alert("Bạn chưa chọn nhân viên để rút khỏi dự án!");
			}
		} else {
			if(regisOrRemoveFlag == 0) {
				for(ProjectStaffDTO pjDTO : pjSDTOList) {
					if(pjDTO.getStatus() != 0) {	// status != 0 (1,2) la nhung nhan vien da duoc xac nhan
						Window.alert("Thực hiện thất bại! Do nhân viên đã tham gia vào dự án!");
						selectionModel.clear();
						return;
					}
				}
			} else if(regisOrRemoveFlag == 1) {
				for (ProjectStaffDTO pjDTO : pjSDTOList) {
					if (pjDTO.getStatus() == 2) {
						Window.alert("Thực hiện thất bại! Do nhân viên đã rút khỏi dự án!");
						selectionModel.clear();
						return;
					}
				}
			}
			userService.getUserList(new AsyncCallback<List<UsersDTO>>() {
				@Override
				public void onSuccess(List<UsersDTO> result) {
					for (UsersDTO user : result) {
						userList.add(user);
					}
					List<ProjectStaffDTO> projectStaffDTOList = new ArrayList<ProjectStaffDTO>();
					for (ProjectStaffDTO projectStaffDTO : listChecked) {
						projectStaffDTOList.add(projectStaffDTO);
					}
					projectStaffService.updateProjectStaff(projectStaffDTOList, userList, _regisOrRemoveFlag,new AsyncCallback<Void>() {
						@Override
						public void onSuccess(Void result) {
							Window.alert("Thực hiện thành công!");
							selectionModel.clear();
							PMEntrypoint.get().PMProjectStaff(pjId);
						}

						@Override
						public void onFailure(Throwable caught) {
							Window.alert("Thực hiện thất bại!");
						}
					});
				}

				@Override
				public void onFailure(Throwable caught) {
					Window.alert("Có lỗi trong quá trình lấy thông tin nhân viên!");
				}
			});
		}
	}
	@UiHandler("btnBack")
	void onBtnBackClick(ClickEvent event) {
		PMEntrypoint.get().PMProjectDetail(pjId);
	}
}
